package com.cdl.library.runnable;

import android.os.Handler;
import android.util.Log;

import com.cdl.library.listener.WriteSdListener;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;


/***
 * 将文件写入SD卡中
 */
public class FileWriteRunnable implements Runnable {

    File mCurrentFile;
    File mTargetFile;
    WriteSdListener listener;
    Handler handler = new Handler();

    public FileWriteRunnable(File currentFile, File targetFile, WriteSdListener listener) {
        this.mCurrentFile = currentFile;
        this.mTargetFile = targetFile;
        this.listener = listener;
    }

    @Override
    public void run() {
        try {
            Log.i("write", "=========开始写入===================");
            InputStream inputStream = new FileInputStream(mCurrentFile);
            // 1.建立通道对象
            FileOutputStream fos = new FileOutputStream(mTargetFile);
            // 2.定义存储空间
            byte[] buffer = new byte[8192];
//            byte[] buffer = new byte[inputStream.available()];
            // 3.开始读文件
            int lenght = 0;
            long sum = 0;
            while ((lenght = inputStream.read(buffer)) != -1) {// 循环从输入流读取buffer字节
                // 将Buffer中的数据写到outputStream对象中
                fos.write(buffer, 0, lenght);
            }
            fos.flush();// 刷新缓冲区
            fos.close();
            inputStream.close();
            backSuccess();
            Log.i("write", "写入完毕=");
        } catch (Exception e) {
            backFailed(e.toString());
            Log.i("write", "写入异常=" + e.toString());
        }
    }

    public void backFailed(final String message) {
        if (listener == null) {
            return;
        }
        handler.post(new Runnable() {
            @Override
            public void run() {
                listener.writeFailed(message);
            }
        });
    }

    public void backSuccess() {
        if (listener == null) {
            return;
        }
        handler.post(new Runnable() {
            @Override
            public void run() {
                listener.writeSuccess(mTargetFile.getAbsolutePath());
            }
        });
    }


}
